/*
 * Copyright (c) 2014 Strong Group - 版权所有
 * 
 * This software is the confidential and proprietary information of
 * Strong Group. You shall not disclose such confidential information 
 * and shall use it only in accordance with the terms of the license 
 * agreement you entered into with www.cnstrong.cn.
 */
package com.zuorenke.serialize.support.json;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.TimeZone;

import com.zuorenke.serialize.ObjectOutput;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;


/**
 *
 * 描述:
 *
 * @author  WQB
 * @created 2014-4-7 上午10:06:19
 * @since   v1.0.0
 */
public class JacksonObjectOutput implements ObjectOutput {

	private final PrintWriter writer;

    private static ObjectMapper mapper = null;
    static {
        if (mapper == null) {
            JsonFactory factory = new JsonFactory();
            mapper = new ObjectMapper(factory);
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            mapper.setTimeZone(TimeZone.getDefault());
        }
    }
    
	public JacksonObjectOutput(OutputStream out) {
		this(new OutputStreamWriter(out));
	}

	public JacksonObjectOutput(Writer writer) {
		this.writer = new PrintWriter(writer);
	}

	public void writeBool(boolean v) throws IOException {
		writeObject(v);
	}

	public void writeByte(byte v) throws IOException {
		writeObject(v);
	}

	public void writeShort(short v) throws IOException {
		writeObject(v);
	}

	public void writeInt(int v) throws IOException {
		writeObject(v);
	}

	public void writeLong(long v) throws IOException {
		writeObject(v);
	}

	public void writeFloat(float v) throws IOException {
		writeObject(v);
	}

	public void writeDouble(double v) throws IOException {
		writeObject(v);
	}

	public void writeUTF(String v) throws IOException {
		writeObject(v);
	}

	public void writeBytes(byte[] b) throws IOException {
		writer.println(new String(b));
	}

	public void writeBytes(byte[] b, int off, int len) throws IOException {
		writer.println(new String(b, off, len));
	}

	public void writeObject(Object obj) throws IOException {
        try {
        	mapper.writeValue(writer, obj);
    		writer.println();
    		writer.flush();
        } catch (JsonGenerationException | JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}

	public void flushBuffer() throws IOException {
		writer.flush();
	}

}